//JavaScript Framework 2.0 Code
try {
	Type.registerNamespace('com.yonyou.ncmm_pac_pda.GeneralOutScanListController');
	com.yonyou.ncmm_pac_pda.GeneralOutScanListController = function() {
		com.yonyou.ncmm_pac_pda.GeneralOutScanListController.initializeBase(this);
		this.initialize();
	}

	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$initialize() {
		//you can programing by $ctx API
		//get the context data through $ctx.get()
		//set the context data through $ctx.push(json)
		//set the field of the context through $ctx.put(fieldName, fieldValue)
		//get the parameter of the context through $ctx.param(parameterName)
		//Demo Code:
		//    var str = $ctx.getString();      //获取当前Context对应的字符串
		//    alert($ctx.getString())          //alert当前Context对应的字符串
		//    var json = $ctx.getJSONObject(); //获取当前Context，返回值为json
		//    json["x"] = "a";        //为当前json增加字段
		//    json["y"] = [];           //为当前json增加数组
		//    $ctx.push(json);            //设置context，并自动调用数据绑定
		//    
		//    put方法需手动调用databind()
		//    var x = $ctx.get("x");    //获取x字段值
		//    $ctx.put("x", "b");     //设置x字段值
		//    $ctx.put("x", "b");     //设置x字段值
		//    $ctx.databind();            //调用数据绑定才能将修改的字段绑定到控件上
		//    var p1 = $param.getString("p1");   //获取参数p2的值，返回一个字符串
		//    var p2 = $param.getJSONObject("p2");   //获取参数p3的值，返回一个JSON对象
		//    var p3 = $param.getJSONArray("p3");   //获取参数p1的值，返回一个数组

		//your initialize code below...

	}

	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$evaljs(js) {
		eval(js)
	}
	//回退
	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$close(sender, args) {
		$view.close();
	}
	//菜单
	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$showMenu(sender, args) {
		NCMMPubMenu.openDropDownList("btn_menu");
	}
	//快速定位
	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$search(sender, args) {
		NCMMPubUtil.quickFilter();
	}
	//选中
	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$doChecked(sender, args) {
		var isCheckedAll = true;
		$ctx.dataCollect();
		var sourceData = $ctx.getJSONArray("scanlist");
		for(var i = 0; i < sourceData.length; i++) {
			if(sourceData[i]["isChecked"] == null || sourceData[i]["isChecked"] == false || sourceData[i]["isChecked"] == "false") {
				isCheckedAll = false;
				for(var j = 0; j < (sourceData[i]["row"]).length; j++) {
					((sourceData[i]["row"])[j])["ischecked"] = false;
				}
			} else {
				for(var j = 0; j < (sourceData[i]["row"]).length; j++) {
					((sourceData[i]["row"])[j])["ischecked"] = true;
				}
			}
		}
		$ctx.put("scanlist", sourceData);
		$ctx.put("isAllChecked", isCheckedAll); //更新全选复选框的界面显示
		$ctx.dataBind();
	}
	//全选
	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$doAllChecked(sender, args) {
		$ctx.dataCollect();
		var isChecked = $id(sender).get("checked");
		var sourceData = $ctx.getJSONArray("scanlist");
		for(var i = 0; i < sourceData.length; i++) {
			sourceData[i]["isChecked"] = isChecked;
			for(var j = 0; j < (sourceData[i]["row"]).length; j++) {
				((sourceData[i]["row"])[j])["ischecked"] = isChecked;
			}
		}

		var json = {};
		json["scanlist"] = sourceData;
		json["isAllChecked"] = isChecked;
		$ctx.push(json); //将数据显示在控件上
	}

	function getQueryRowSql() {
		var sql = "SELECT " +
			GeneralOutScanVO.VBILLCODE.name + ", " + GeneralOutScanVO.CROWNO.name + ", " +
			GeneralOutScanVO.MATERIALNAME.name + ", " + GeneralOutScanVO.NSCANNUM.name +
			" FROM " + GeneralOutScanVO.prototype.getTableName() +
			" group by " + GeneralOutScanVO.VBILLCODE.name + ", " + GeneralOutScanVO.CROWNO.name;

		return sql;
	}

	function getOutScanVOsBySql(data) {
		var rtn = new Array();
		var bitnumberJson = {};
		Array.prototype.map.call(data, function(vo) {
			var vbillcode = vo[GeneralOutScanVO.VBILLCODE.name];
			var crowno = vo[GeneralOutScanVO.CROWNO.name];
			var wheresql = "where " + GeneralOutScanVO.VBILLCODE.name + "='" + vbillcode + "' and " + GeneralOutScanVO.CROWNO.name + "='" + crowno + "' ";
			var sum = 0;
			var cunitid = "";
			NCMMPubUtil.queryVO(GeneralOutScanVO, wheresql, function(data) {
				var showData = eval(data);
				  showData = NCMMPubUtil.htmlspecialjsonarray2UI(showData);
				var bitnumberJson = {};
				if(NCMMPubUtil.isNotEmpty(showData)) {
					for(var i = 0; i < showData.length; i++) {
						var itemData = showData[i];
						if(NCMMPubUtil.isEmpty(bitnumberJson) || NCMMPubUtil.isEmpty(bitnumberJson[itemData["cunitid"]])) {
							var bitnumber = NCMMPubUtil.getUnitBitnumber(itemData["cunitid"]);
							if(!NCMMPubUtil.isEmpty(bitnumber)) {
								bitnumberJson[itemData["cunitid"]] = bitnumber;
							}
						}
						if(NCMMPubUtil.isEmpty(bitnumberJson) || NCMMPubUtil.isEmpty(bitnumberJson[itemData["castunitid"]])) {
							var bitnumber = NCMMPubUtil.getUnitBitnumber(itemData["castunitid"]);
							if(!NCMMPubUtil.isEmpty(bitnumber)) {
								bitnumberJson[itemData["castunitid"]] = bitnumber;
							}
						}
						if(!NCMMPubUtil.isEmpty(bitnumberJson) && !NCMMPubUtil.isEmpty(bitnumberJson[itemData["cunitid"]])) {

							showData[i]["nnum"] = parseFloat(showData[i]["nnum"]).toFixed(bitnumberJson[itemData["cunitid"]]);
							showData[i]["nscannum"] = parseFloat(showData[i]["nscannum"]).toFixed(bitnumberJson[itemData["cunitid"]]);
						}
						if(!NCMMPubUtil.isEmpty(bitnumberJson) && !NCMMPubUtil.isEmpty(bitnumberJson[itemData["castunitid"]])) {
							showData[i]["nastnum"] = parseFloat(showData[i]["nastnum"]).toFixed(bitnumberJson[itemData["castunitid"]]);
							showData[i]["nscanastnum"] = parseFloat(showData[i]["nscanastnum"]).toFixed(bitnumberJson[itemData["castunitid"]]);
						}

						var scanednum = showData[i][GeneralOutScanVO.NSCANNUM.name];
						//$alert("sum=" + sum.toString() + " scanednum=" + scanednum);
						sum = NCMMPubUtil.getAddNum(sum, scanednum);

					}
					cunitid = showData[0]["cunitid"];
				}

				vo["row"] = showData;
				if(NCMMPubUtil.isEmpty(bitnumberJson) || NCMMPubUtil.isEmpty(bitnumberJson[cunitid])) {
					var bitnumber = NCMMPubUtil.getUnitBitnumber(cunitid);
					if(!NCMMPubUtil.isEmpty(bitnumber)) {
						bitnumberJson[cunitid] = bitnumber;
					}
				}
				if(!NCMMPubUtil.isEmpty(bitnumberJson) && !NCMMPubUtil.isEmpty(bitnumberJson[cunitid])) {
					sum = parseFloat(sum).toFixed(bitnumberJson[cunitid]);
				}

				vo["sumScanedNum"] = sum;
				rtn.push(vo);

			});
		});
		return rtn;
	}
	//查询本地扫描记录
	function loadScanListData() {
		//按照订单号和行号分组查询
		var sql = getQueryRowSql();
		var data = NCMMPubUtil.queryBySQL(sql);
		data = eval(data);
		var scangroups = getOutScanVOsBySql(data);
		//$alert("scangroups="+$jsonToString({scangroups:scangroups}));
		//显示
		$ctx.push({
			scanlist: scangroups
		});

	}
	//加载
	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$loadScanList(sender, args) {
		// 加载数据的时候判断如果有表则查询，如果不存在数据表则先创建
		NCMMPubUtil.createTable(GeneralOutScanVO);
		loadScanListData();

	}
	var popDialogInfo = {
		"viewid": "panel_btn", //显示的控件的id，通常是一个容器控件div
		"popgravity": "popbottom", //popcenter|poptop|popbottom|popleft|popright,弹出后最终显示的位置
		// istouch : 'false'
	};
	//列表行点击
	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$showItemButton(sender, args) {
		var row = {};
		row = $id("scanlistview").get("row");
		row = $stringToJSON(row);
		if(row && row["row"])
			return;
		$view.openPop(popDialogInfo);
	}

	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$showDetail(sender, args) {
		$view.closePop(popDialogInfo);
		var row = $id("scanlistview").get("row");
		//row = $stringToJSON(row);
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.GeneralOutScanDetail", //目标页面（首字母大写）全名
			"isKeep": "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
			"row": row
		});
	}

	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$itemDelete(sender, args) {
		$view.closePop(popDialogInfo);
		var params = {
			"title": "提示",
			"message": "确定删除所选记录吗？",
			"okbuttontitle": "确定",
			"cancelbuttontitle": "取消",
			"style": "ok-cancel",
			"okaction": "doDelete()",
			"cancelaction": "doCancel()"
		};
		$view.openDialog(params);
	}

	function doCancel() {
		$toast("删除操作已取消。");
	}

	//执行清除操作
	function doDelete() {
		var row = $id("scanlistview").get("row");
		row = $stringToJSON(row);
		NCMMPubUtil.deleteVO(GeneralOutScanVO, row);
		//更新发货单入库列表增加扫描数量 
		GeneralOutUtil.updateScanedNum(row.pk_item);
		$toast("删除成功。");
		loadScanListData();
	}

	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$doEdit(sender, args) {
		$view.closePop(popDialogInfo);
		var row = $id("scanlistview").get("row");
		//row = $stringToJSON(row);
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.GeneralOutScan", //目标页面（首字母大写）全名
			"isKeep": "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
			"row": row,
			"isEdit":true
		});
	}

	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$itemCancel(sender, args) {
		$view.closePop(popDialogInfo);
	}
	//提交
	function com$yonyou$ncmm_pac_pda$GeneralOutScanListController$doCommit(sender, args) {
		var isCommitByStordoc=false;
		var stordoc = $cache.read("defaultstordoc");
		if(NCMMPubUtil.isNotEmpty(stordoc)) {
		  isCommitByStordoc=true;
			//$alert("默认仓库不能为空，请设置！");
			//return;
		}

		//连接验证成功后的后续处理
		$js.showLoadingBar();
		$ctx.dataCollect();
		var sourceData = $ctx.getJSONArray("scanlist");
		var scanCount = {};
		var scanNum = {};
		var nScanedNumAndBids = {};
		var nScanedAstNumAndBids = {};
		var itemPKs = [];
		var headJson = {};
		var itemJson = {};
		var bbitemJson = {};
		var itemKeyJson = {};
		var needCommit = false;
		var headKey = [];
		for(var i = 0; i < sourceData.length; i++) {
			//过滤出需要下载的档案
			if(sourceData[i]["isChecked"] != null && (sourceData[i]["isChecked"] == true || sourceData[i]["isChecked"] == "true")) {
				needCommit = true;
				for(var j = 0; j < sourceData[i]["row"].length; j++) {
					var json = sourceData[i]["row"][j];
					var itemKey = json.pk_item + json.vbatchcode;
					itemPKs.push(json.pk_item);
					//增加扫描记录数
					if(NCMMPubUtil.isEmpty(scanCount[json.pk_item])) {
						scanCount[json.pk_item] = 1;
					} else {
						scanCount[json.pk_item] = scanCount[json.pk_item] + 1;
					}
					//增加扫描累计
					if(NCMMPubUtil.isEmpty(scanNum[json.pk_item])) {
						scanNum[json.pk_item] = json.nscannum;
					} else {
						scanNum[json.pk_item] = NCMMPubUtil.getAddNum(scanNum[json.pk_item], json.nscannum);
					}
					//处理头map
					if(NCMMPubUtil.isEmpty(headJson) || NCMMPubUtil.isEmpty(headJson[json.pk_head])) {
						var head = {};
						head["cgeneralhid"] = json.pk_head;		
						head["hts"]=json.hts;				
						headJson[json.pk_head] = head;
						headKey.push(json.pk_head);
						itemKeyJson[json.pk_head] = [];
						isCommitByStordoc=isCommitByStordoc||NCMMPubUtil.isNotEmpty(json.cwarehouseid)
					}
					//处理体Map			
					if(NCMMPubUtil.isEmpty(itemJson) || NCMMPubUtil.isEmpty(itemJson[itemKey])) {
						var item = {};						
						item["cgeneralbid"] = json.pk_item;
						item["cmaterialvid"] = json.cmaterialvid;
						item["castunitid"] = json.castunitid;
						item["vbatchcode"] = json.vbatchcode;
						item["nscannum"] = json.nscannum;
						item["nscanastnum"] = json.nscanastnum;
						item["bts"] = json.bts;
						item["vbnote"] = json.vbnote;
						itemJson[itemKey] = item;
						var newItemKey = itemKeyJson[json.pk_head];
						newItemKey.push(itemKey);
						itemKeyJson[json.pk_head] = newItemKey;					

					} else {
						var newItem = itemJson[itemKey];
						newItem.nscannum = NCMMPubUtil.getAddNum(newItem.nscannum, json.nscannum);
						newItem.nscanastnum = NCMMPubUtil.getAddNum(newItem.nscanastnum, json.nscanastnum);
						itemJson[itemKey] = newItem;
					}
					if (NCMMPubUtil.isNotEmpty(nScanedNumAndBids) && NCMMPubUtil.isNotEmpty(nScanedNumAndBids[json.pk_item])) {
							var nScanedNum = NCMMPubUtil.getAddNum(nScanedNumAndBids[json.pk_item], json.nscannum);
							nScanedNumAndBids[json.pk_item] = nScanedNum;
					} else {
							nScanedNumAndBids[json.pk_item] = json.nscannum;
					}
					if (NCMMPubUtil.isNotEmpty(nScanedAstNumAndBids) && NCMMPubUtil.isNotEmpty(nScanedAstNumAndBids[json.pk_item])) {
							var nScanedastNum = NCMMPubUtil.getAddNum(nScanedAstNumAndBids[json.pk_item], json.nscanastnum);
							nScanedAstNumAndBids[json.pk_item] = nScanedastNum;
					} else {
							nScanedAstNumAndBids[json.pk_item] = json.nscanastnum;
					}
					//处理序列号
					if(!NCMMPubUtil.isEmpty(json.vserialcode) ||!NCMMPubUtil.isEmpty(json.pk_rack)
					) {
						var bbitem = {};
						//bbitem["pk_serialcode"] = json.pk_serialcode;
						bbitem["vserialcode"] = json.vserialcode;
						bbitem["nnum"] = json.nscannum;
						bbitem["nassistnum"] = json.nscanastnum;
						bbitem["clocationid"] = json.pk_rack;
						// bbitem["clocationid"]=json.pk_rack;
						if(NCMMPubUtil.isEmpty(bbitemJson) || NCMMPubUtil.isEmpty(bbitemJson[itemKey])) {
							bbitemJson[itemKey] = [bbitem];
						} else {
							var newBbitem = bbitemJson[itemKey];
							newBbitem.push(bbitem);
							bbitemJson[itemKey] = newBbitem;
						}
					}
				}
			}
		}
		if(needCommit == false) {
			$js.hideLoadingBar();
			$toast("没有选中任何记录！");
			return;
		}
		var checkResult = GeneralOutUtil.checkWhenCommit(itemPKs, scanCount, scanNum);
		if(!NCMMPubUtil.isEmpty(checkResult)) {
			$js.hideLoadingBar();
			$alert(checkResult);
			return;
		}
		if(isCommitByStordoc){
		   var billinfos = getBillInfos(headKey, headJson, itemKeyJson, itemJson, bbitemJson);
		   //提交
		   GeneralOutUtil.commitData(billinfos, function(billbids) {	
			 loadScanListData();
		  });
		 }
		 else{
		     $js.hideLoadingBar();
		     $alert("仓库不能为空，请设置！");
            return;
		 }

	}
	function getBillInfos(headKey, headJson, itemKeyJson, itemJson, bbitemJson) {
		var billinfos = [];
		for(var i = 0; i < headKey.length; i++) {
			var head = headJson[headKey[i]];
			var itemkeys = itemKeyJson[headKey[i]];
			var items = getItems(itemkeys, itemJson, bbitemJson);
			var billinfo = {
				"head": head,
				"items": items
			};
			billinfos.push({
				"billinfo": billinfo
			});
		}
		return billinfos;
	}

	function getItems(itemkeys, itemJson, bbitemJson) {
		var items = [];
		for(var i = 0; i < itemkeys.length; i++) {
			var item = itemJson[itemkeys[i]];
			if(!NCMMPubUtil.isEmpty(bbitemJson) && !NCMMPubUtil.isEmpty(bbitemJson[itemkeys[i]])) {
				//处理bbitem
				var bbitemArr = bbitemJson[itemkeys[i]];
				var bbitems = getBbitems(bbitemArr);
				item["bbitems"] = bbitems;
			}
			items.push({
				"item": item
			});
		}
		return items;
	}

	function getBbitems(bbitemArr) {
		var bbitems = [];
		for(var i = 0; i < bbitemArr.length; i++) {
			var bbitem = {
				"bbitem": bbitemArr[i]
			};
			bbitems.push(bbitem);
		}
		return bbitems;
	}
	com.yonyou.ncmm_pac_pda.GeneralOutScanListController.prototype = {
		doCommit: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$doCommit,
		showDetail: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$showDetail,
		doEdit: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$doEdit,
		itemDelete: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$itemDelete,
		itemCancel: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$itemCancel,
		showItemButton: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$showItemButton,
		loadScanList: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$loadScanList,
		doAllChecked: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$doAllChecked,
		doChecked: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$doChecked,
		search: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$search,
		showMenu: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$showMenu,
		close: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$close,
		initialize: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$initialize,
		evaljs: com$yonyou$ncmm_pac_pda$GeneralOutScanListController$evaljs
	};
	com.yonyou.ncmm_pac_pda.GeneralOutScanListController.registerClass('com.yonyou.ncmm_pac_pda.GeneralOutScanListController', UMP.UI.Mvc.Controller);
} catch(e) {
	$e(e);
}